package com.jstyle.jclifexd.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.HealthHistoryActivity;
import com.jstyle.jclifexd.adapter.HealthShowAdapter;
import com.jstyle.jclifexd.adapter.HrvDataAdapter;
import com.jstyle.jclifexd.daoManager.HealthDataDaoManager;
import com.jstyle.jclifexd.model.HealthData;
import com.jstyle.jclifexd.utils.BloodMaxComparator;
import com.jstyle.jclifexd.utils.BloodMinComparator;
import com.jstyle.jclifexd.utils.ChartDataUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.ResolveData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import lecho.lib.hellocharts.model.BpValue;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HealthHistoryDayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HealthHistoryDayFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.ColumnChartView_history)
    ColumnChartView ColumnChartViewHistory;
    @BindView(R.id.LineChartView_history)
    LineChartView LineChartViewHistory;
    @BindView(R.id.RecyclerView_history_detail)
    RecyclerView RecyclerViewHistoryDetail;
    @BindView(R.id.bt_history_dataType)
    Button btHistoryDataType;
    @BindView(R.id.RecyclerView_history)
    RecyclerView RecyclerViewHistory;
    Unbinder unbinder;
    @BindArray(R.array.health_hrv)
    String[] arrayHrv;
    @BindArray(R.array.health_pressure)
    String[] arrayPressure;
    @BindArray(R.array.health_blood)
    String[] arrayBlood;
    @BindView(R.id.ll_health_bp)
    LinearLayout llHealthBp;
    @BindView(R.id.tv_noData)
    TextView tvNoData;
    // TODO: Rename and change types of parameters
    private int mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ArrayList<String> listContent;
    private HealthShowAdapter historyShowAdapter;

    public HealthHistoryDayFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment HealthHistoryDayFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HealthHistoryDayFragment newInstance(int param1,String date) {
        HealthHistoryDayFragment fragment = new HealthHistoryDayFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, date);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    int dataType=0;
    @Override
    public void updateDate(String queryDate, int dataType) {
        List<HealthData> healthDataList = HealthDataDaoManager.queryDayData(queryDate);
        this.dataType=dataType;
        if (dataType == HealthHistoryActivity.DATA_BLOOD) {
            initChartViewBlood(healthDataList, queryDate);
        } else {
            initChartView(healthDataList, queryDate, dataType);
        }
        initRecyclerViewHistory(healthDataList);
    }

    private void initRecyclerViewHistory(List<HealthData> healthDataList) {//底部详细数据
        HrvDataAdapter hrvDataAdapter = new HrvDataAdapter(healthDataList);
        hrvDataAdapter.setDataType(mParam1);
        RecyclerViewHistory.setAdapter(hrvDataAdapter);
    }

    private void initChartView(List<HealthData> healthDataList, String queryDate, int dateType) {
        int count = 0;
        int totalDayHr = 0;
        int maxDayHr = 0;
        int minDayHr = 300;
        int[] healthArray = new int[1440];
        List<HealthData>healthDataTemp=new ArrayList<>();
        for (int i = 0; i < healthDataList.size(); i++) {
            HealthData heartData = healthDataList.get(i);
            int data=ChartDataUtil.getHealthData(dateType,heartData);
            if(data==0)healthDataTemp.add(heartData);
            String date = heartData.getTime();
            int startCount = DateUtil.get1MIndex(date, queryDate + " 00:00:00");
            int heartRate = ResolveData.getData(heartData, dateType);
            if (heartRate != 0) {
                count++;
                totalDayHr += heartRate;
                maxDayHr = Math.max(maxDayHr, heartRate);
                minDayHr = Math.min(minDayHr, heartRate);
            }
            healthArray[startCount] = heartRate;
        }
        healthDataList.removeAll(healthDataTemp);
        int avgHR = count == 0 ? 0 : totalDayHr / count;
        int[] maxHeartArray = new int[24];
        for (int i = 0; i < 24; i++) {
            int start = i * 60;
            int totalHr = 0;
            int countHr = 0;
            for (int j = 0; j < 60; j++) {//每小时的平均值
                int hr = healthArray[j + start];
                if (hr != 0) {
                    totalHr += hr;
                    countHr++;
                }
            }
            maxHeartArray[i] = countHr == 0 ? 0 : totalHr / countHr;
        }
        if(count==0){

            ColumnChartViewHistory.setVisibility(View.GONE);
            LineChartViewHistory.setVisibility(View.GONE);
            tvNoData.setVisibility(View.VISIBLE);
        }else{
            ColumnChartViewHistory.setVisibility(dataType==HealthHistoryActivity.DATA_BLOOD?View.VISIBLE:View.GONE);
            LineChartViewHistory.setVisibility(dataType==HealthHistoryActivity.DATA_BLOOD?View.GONE:View.VISIBLE);
            tvNoData.setVisibility(View.GONE);

        }
        int top=(maxDayHr/10+1)*10;
        ChartDataUtil.initDataChartView(LineChartViewHistory, -0.5f, top+5, healthDataList.size(), 0);
        LineChartViewHistory.setLineChartData(ChartDataUtil.getHealthDayLineChart( mParam1, healthDataList,top));
        List<String> listHeart = new ArrayList<>();//总计列表
        listHeart.add(avgHR + "");
        listHeart.add(maxDayHr + "");
        listHeart.add((minDayHr == 300 ? 0 : minDayHr) + "");
        historyShowAdapter.setStepData(listHeart);
    }

    private static final String TAG = "HealthHistoryDayFragmen";

    private void initChartViewBlood(List<HealthData> healthDataList, String queryDate) {

        int totalDayHr = 0;
        int maxDayHr = 0;
        int minDayHr = 300;

        List<BpValue> listBpValue = new ArrayList<>();
        HealthData maxHealthData = null;
        HealthData minHealthData = null;
        for (int i = 0; i < healthDataList.size(); i++) {
            HealthData heartData = healthDataList.get(i);
            String date = heartData.getTime();
            String time = date.split(" ")[1];
            int highValue = heartData.getHighBloodPressure();
            int lowValue = heartData.getLowBloodPressure();
            BpValue bpValue = new BpValue(highValue, lowValue);
            bpValue.setDate(time);
            listBpValue.add(bpValue);

        }
        if(listBpValue.size()==0){
            ColumnChartViewHistory.setVisibility(View.GONE);
            tvNoData.setVisibility(View.VISIBLE);
        }else{
            ColumnChartViewHistory.setVisibility(View.VISIBLE);
            tvNoData.setVisibility(View.GONE);
            Collections.sort(healthDataList,new BloodMaxComparator());
            maxHealthData=healthDataList.get(healthDataList.size()-1);
            Collections.sort(healthDataList,new BloodMinComparator());
            minHealthData=healthDataList.get(0);
        }
        ChartDataUtil.initDataChartView(ColumnChartViewHistory, -0.5f, 190, listBpValue.size() < 12 ? 12 : listBpValue.size() + 0.5f, 20);
        ColumnChartViewHistory.setColumnChartData(ChartDataUtil.getHealthDayBloodColumnChart(getActivity(), listBpValue, maxDayHr * 1.2f));
        List<String> listHeart = new ArrayList<>();//总计列表
        listHeart.add(listBpValue.size() + "");
        String highDay = maxHealthData == null ? "--/--" : maxHealthData.getHighBloodPressure() + "/" + maxHealthData.getLowBloodPressure();
        String lowDay = minHealthData == null ? "--/--" : minHealthData.getHighBloodPressure() + "/" + minHealthData.getLowBloodPressure();
        listHeart.add(highDay);
        listHeart.add(lowDay);
        historyShowAdapter.setStepData(listHeart);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_health_day, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void setListContent() {
        listContent = new ArrayList<>();
        String[] arrayContent = null;
        switch (mParam1) {
            case HealthHistoryActivity.DATA_BLOOD:
                arrayContent = arrayBlood;
                break;
            case HealthHistoryActivity.DATA_HRV:
                arrayContent = arrayHrv;
                break;
            case HealthHistoryActivity.DATA_PRESSURE:
                arrayContent = arrayPressure;
                break;
        }
        listContent.addAll(Arrays.asList(arrayContent));

    }


    private void init() {
        GridLayoutManager layoutManager2 = new GridLayoutManager(getActivity(), 3);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        setListContent();
        historyShowAdapter = new HealthShowAdapter(listContent);
        RecyclerViewHistoryDetail.setAdapter(historyShowAdapter);
        RecyclerViewHistoryDetail.setLayoutManager(layoutManager2);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewHistory.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        ColorDrawable colorDrawable = new ColorDrawable();
        colorDrawable.setColor(Color.DKGRAY);
        dividerItemDecoration.setDrawable(colorDrawable);
        RecyclerViewHistory.addItemDecoration(dividerItemDecoration);
        String queryDate = TextUtils.isEmpty(mParam2)? DateUtil.getDefaultFormatTime(new Date()):mParam2;
        llHealthBp.setVisibility(mParam1 == HealthHistoryActivity.DATA_BLOOD ? View.VISIBLE : View.GONE);
        updateDate(queryDate, mParam1);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
